package com.gitee.fsmxm.ocon.converter;

import com.jacob.com.Dispatch;
import com.gitee.fsmxm.ocon.constant.XlFixedFormatQuality;
import com.gitee.fsmxm.ocon.constant.XlPageOrientation;
import com.gitee.fsmxm.ocon.core.Converter;
import com.gitee.fsmxm.ocon.model.ConParam;
import com.gitee.fsmxm.ocon.model.Procedure;
import com.gitee.fsmxm.ocon.util.ExcelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * excel open document and convert to ..
 *
 * @author fsmxm
 */
public class ExcelConverter implements Converter {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelConverter.class);

    @Override
    public void convert(Procedure procedure, ConParam param) {
        Dispatch workbook = null;
        try {
            Dispatch workbooks = procedure.getDispatch();
            workbook = Dispatch.invoke(workbooks, "Open", Dispatch.Method, ExcelUtils.paramOfOpen(param.getSource().getFile().getAbsolutePath()), new int[1]).toDispatch();
            Dispatch sheets = Dispatch.get(workbook, "Sheets").toDispatch();
            if ("pdf".equals(param.getTarget().getExt())) {
                int count = Dispatch.get(sheets, "Count").getInt();
                for (int i = 1; i <= count; i++) {
                    Dispatch sheet = Dispatch.invoke(sheets, "Item", Dispatch.Get, new Object[]{i}, new int[1]).toDispatch();
                    Dispatch pageSetup = Dispatch.get(sheet, "PageSetup").toDispatch();
                    Dispatch.invoke(pageSetup, "Orientation", Dispatch.Put, new Object[]{XlPageOrientation.XL_LANDSCAPE}, new int[1]);
                    Dispatch.invoke(pageSetup, "Zoom", Dispatch.Put, new Object[]{false}, new int[1]);
                    Dispatch.invoke(pageSetup, "FitToPagesWide", Dispatch.Put, new Object[]{1}, new int[1]);
                    Dispatch.invoke(pageSetup, "FitToPagesTall", Dispatch.Put, new Object[]{false}, new int[1]);
                }
                Dispatch.invoke(workbook, "ExportAsFixedFormat", Dispatch.Method, new Object[]{0, param.getTarget().getFile().getAbsolutePath(), XlFixedFormatQuality.XL_QUALITY_STANDARD}, new int[1]);
            } else {
                Dispatch.invoke(workbook, "SaveAs", Dispatch.Method, ExcelUtils.paramOfSaveAs(param.getTarget().getFile().getAbsolutePath(), ExcelUtils.getFormatType(param.getTarget().getExt())), new int[1]);
            }
        } finally {
            if (workbook != null) {
                // TODO The Close & Saved method sometimes calls problem : 0x8001010A. The message filter indicated that the application is busy.
                try {
                    Dispatch.call(workbook, "Close", false);
                    workbook.safeRelease();
                } catch (Exception e) {
                    LOGGER.warn("exception: ", e);
                }
            }
        }
    }

}
